package com.kehao.leetcode.middle.tree_graph;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class MiddleOrderIterateSolution {
    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    //递归法
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        putIntoList(root,result);
        return result;
    }

    private void putIntoList(TreeNode root, List<Integer> result) {
        if(root==null) return;
        putIntoList(root.left,result);
        result.add(root.val);
        putIntoList(root.right,result);
    }

    //非递归
    public List<Integer> inorderTraversal1(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        while (root!=null){
            stack.push(root);
            root = root.left;
        }
        while (!stack.isEmpty()){
            TreeNode pop = stack.pop();
            result.add(pop.val);
            TreeNode p  = pop.right;
            while (p!=null){
                stack.push(p);
                p=p.left;
            }
        }
        return result;
    }


    @Test
    public void test01(){
        TreeNode treeNode1 = new TreeNode(1);
        TreeNode treeNode2 = new TreeNode(2);
        TreeNode treeNode3 = new TreeNode(3);
        treeNode1.right = treeNode2;
        treeNode2.left = treeNode3;
        System.out.println(inorderTraversal1(treeNode1));
    }

}
